<?php
/**
 * 活动管理
 */
namespace Admin\Controller;
use Admin\BaseController;
use Common\Model\BusinessModel;
use Common\Model\CommentModel;
use Common\Model\EditorModel;
use Common\Model\SmsModel;
use Common\Model\UserModel;
use Common\Model\UtilsModel;
use Common\Model\EventsModel;
use Common\Model\WeixinModel;
use Think\Page;
/*Ajax异步获取数据Action*/
class EventsController extends BaseController{

	/**
	 * 活动列表页
	 * Author: shijy
	 */
	public function index(){
		$where=' 1 AND del = 0 ';
		$actype = I('get.actype','ing','trim');
		$newTime = time();
		switch ($actype){
			case 'ing': $where .= " and applyStartTime < $newTime AND applyEndTime > $newTime"; break;
			case 'wait': $where .= " and applyStartTime > $newTime"; break;
			case 'end': $where .= " and applyEndTime < $newTime"; break;
		}

		$keywords=I('get.keywords','');
		if(strlen($keywords)>0){
			$where .= " and title like '%{$keywords}%'";
		}

		$eventsM = M("e_events",null,DB_MAIN_CFG);
		import("ORG.Util.Page");

		$temp=$eventsM->where($where);
		$count = $temp->count();
		$this->smarty->assign('totalDataCount',$count);

		$limit = I('get.limit',10,'int');	//每页显示条数
		$Page = new Page($count,$limit);
		fetchPage($this->smarty, $Page);

		$list = $eventsM->order('beginShowTime DESC')->where($where)->limit($Page->firstRow.','.$Page->listRows)->select();

		$eventsJoinM = M("e_events_join",null,DB_MAIN_CFG);
		foreach ($list as $ky => $val){
			$list[$ky]['applyCount'] = $eventsJoinM->where("eid={$val['id']} AND del = 0")->count();
			$list[$ky]['applyUnjoinCount'] = $eventsJoinM->where('eid='.$val['id'].' AND status ='.EventsModel::JOIN_STATUS_UNJOIN." AND del = 0")->count();//放鸽子
		}

		$this->smarty->assign('limit',$limit);
		$this->smarty->assign('keywords',$keywords);
		$this->smarty->assign('getLevelKv',getLevelKv());
		$this->smarty->assign('list',$list);
		$this->smarty->assign('action','index');
		$this->smarty->assign('actype',$actype);

		$this->smarty->assign('originalPriceSwitch',EVENT_ORIGINAL_PRICE);
		$this->smarty->assign('currentPriceSwitch',EVENT_CURRENT_PRICE);
		$this->smarty->assign('userLevelSwitch',EVENT_ASK_USERLEVEL);

		$this->smarty->display('Events/index.html');
	}

	//活动编辑页
	public function edit(){
		$uid = session(C('USER_AUTH_KEY'))+0;
		$id=I('post.id',0,'int');
		unset($_POST['id']);
		$data = $_POST;

		$channel = I('post.channel',null);
		$needChannelNum = C('EVENT_CHANNEL_BELONG_NUM')+0;
		if(count($channel) < $needChannelNum){
			$this->ajaxReturn(array('status' =>1,'msg'=>"至少从属{$needChannelNum}个栏目！"));
		}

		if(EVENT_CLIENT_SHOW){
			$clientShow=I('post.clientShow',null);
			if(count($clientShow)<=0){
				$this->ajaxReturn( array('status'=>1, 'msg'=> '文章必须指定至少一个展现渠道！') );
			}
			$data['clientShow']=implode(',',$clientShow);
		} else{
			$data['clientShow']=CLIENT_SHOW_WAP;
		}

		if(EVENT_BUSINESS){
			$business = I('post.business',0,'intval');
		}
		else {
			$business = 0;
		}


		//自动完成 将时间自动转换为时间戳
		$content=htmlspecialchars_decode(I('post.content'));
		$nativeRT	= UtilsModel::NativeThumb($content);
		$relativePhoto	= $nativeRT[0];
		$content		= $nativeRT[1];

        $content = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $content);
        $data['content'] = $content;
		$data['relativePhoto'] = implode(',',$relativePhoto );
		$data['beginShowTime'] = I('post.beginShowTime',null,'strtotime');
		$data['applyStartTime'] = I('post.applyStartTime',null,'strtotime');
		$data['applyEndTime'] = I('post.applyEndTime',null,'strtotime');
		$data['title'] = I('post.title', null, 'strip_tags');
		$data['channel'] = implode(',',$channel);
		$data['jumpMode'] = I('post.jumpMode',0,'int');
		$data['needAge'] = I('post.needAge',0,'int');
		$data['needDeliver'] = I('post.needDeliver',0,'int');
		$data['showPay'] = I('post.showPay','免费','htmlspecialchars');
		$data['task'] = I('post.task',0,'intval');
		$data['businessManager'] = $business;
		$data['editor'] = $uid;
		$data['mustFollow'] = 1;//无论前台怎么设置，要求必须关注


        $ftitle=I('post.field_title',null);
        $ftip=I('post.field_tip',null);
        if (is_array($ftitle)){
            $jsonData=array();
            foreach ($ftitle as $k=>$v){
                $jsonData[]=array('title'=>$v,'tip'=>isset($ftip[$k])?$ftip[$k]:'');
            }
            $data['jsonData']=json_encode($jsonData);
        }


		if($data['jumpMode']==EventsModel::JUMP_MODE_NO){
			$data['jumpURL'] = '';
		}else{
			$data['jumpURL'] = I('post.jumpURL','');
			if($data['jumpURL']==''){
				$this->ajaxReturn( array('status'=>1, 'msg'=> '请输入跳转地址！') );
			}
		}


		$rawShowListTime=I('post.showListTime');
		if(!$rawShowListTime){
			$this->ajaxReturn(array('status'=>1,'msg'=>'请按规格输入活动时间'));
		}


		//商务评价
		if($business >0){
			$commerceM = M('commerce_evaluate',null,DB_MAIN_CFG);
			$editorName =  M("gm_sys_user",null,DB_GM_CFG)->where("id={$uid}")->getField("username");
			$commerceName = M('u_user_base',null,DB_MAIN_CFG)->where("uid={$business}")->getField("realName");
			$info['title'] = $data['title'];
			$info['editorName'] = $editorName;
			$info['commerceID'] = $business;
			$info['commerceName'] = $commerceName;
			$info['status'] = EditorModel::COMMERCE_EVALUATE_OFF;
		}




		$events = M('e_events',null,DB_MAIN_CFG);
		if($id){
			$events->where("id=$id")->save($data);
			//商务信息修改
			if($business > 0){
				$commerceM->where("objType=".OBJ_TYPE_ARTICLE." and objID={$id}")->save($info);
			}
			$this->ajaxReturn( array('status'=>0, 'msg'=> '活动修改成功！', 'id'=>$id) );
		}else{
			$row = $events->where("title='{$data['title']}'")->find();
			if($row) $this->ajaxReturn( array('status'=>1, 'msg'=> '该活动名称已存在！') );
			$data['addTime'] = time();
			$insertid = $events->add($data);
			//商务信息保存
			if($business > 0){
				$info['objType'] = OBJ_TYPE_ARTICLE;
				$info['objID'] = $insertid;
				$commerceM->add($info);
			}
			$this->ajaxReturn( array('status'=>0, 'msg'=> '新增活动成功！', 'id'=>$insertid) );
		}

	}

	//活动添加页
	public function add(){
		$id=I('get.id',0,'int');

		if($id){
			$events = M('e_events',null,DB_MAIN_CFG);
			$data = $events->where("id=$id")->find();
			$this->smarty->assign('data', $data);
			$this->smarty->assign('id', $id);

			$selectedClient=explode(',',$data['clientShow']);
			$this->smarty->assign('selectedClients',$selectedClient);

			$selectedChannel=explode(',',$data['channel']);
			$this->smarty->assign('selectedChannels',$selectedChannel);

			$this->smarty->assign('selectedSysUser',$data['businessManager']);

			$ext=json_decode($data['jsonData'],1);
            $this->smarty->assign('ext',$ext);
		}

		//展现渠道
		if(EVENT_CLIENT_SHOW){
			$clientShow=array_slice(C('CLIENT_SHOW'),1,null,true);
			$this->smarty->assign('clientShow',$clientShow);
		}

		//商务经理
		if(EVENT_BUSINESS){
			$sysUser = getBusinessMangerList();
			$this->smarty->assign('sysUser',$sysUser);
		}

		$pointMall=M('point_mall',null,DB_MAIN_CFG)->field('id,titleInner')->limit(20)->select();
		$this->smarty->assign('pointMall',$pointMall );
		//用户等级
		if(EVENT_ASK_USERLEVEL){
			$this->smarty->assign('userLevel',getLevelKv() );
		}
		$this->smarty->assign('askUserLevel',EVENT_ASK_USERLEVEL);
		$this->smarty->assign('randomModel',EVENT_TYPE_RANDOM);
		$this->smarty->assign('originalPriceSwitch',EVENT_ORIGINAL_PRICE);
		$this->smarty->assign('currentPriceSwitch',EVENT_CURRENT_PRICE);
		$this->smarty->assign('clientShowSwitch',EVENT_CLIENT_SHOW);
		$this->smarty->assign('handInTask',EVENT_HANDIN_TASK);
		$this->smarty->assign('businessSwitch',EVENT_BUSINESS);		//活动商务经理开关

		$this->smarty->assign('eventsType',getContentTypeKv() );
		$channels=getChannelKv(OBJ_TYPE_ACTIVITY);
		$this->smarty->assign('channels',$channels);
		$this->smarty->assign('picWidth', C("EVENTS_THUMB_WIDTH"));
		$this->smarty->assign('picHeight', C("EVENTS_THUMB_HEIGHT"));
		$this->smarty->assign('storeKv',BusinessModel::getStoreKv() );



		$this->smarty->display('Events/edit.html');
	}



	//删除活动
	public function del(){
		$id=I('get.id',0,'int');
		if(M('e_events',null,DB_MAIN_CFG)->where(" id = '{$id}'")->save(array("del"=>1))){
			$this->ajaxReturn( array('status'=>0, 'msg'=> '删除成功！') );
		}else{
			$this->ajaxReturn( array('status'=>1, 'msg'=> '删除失败！请联系管理员') );
		}
	}

	//类型管理
	public function eventsTypeManage(){
		$data = M('cfg_content_type',null,DB_MAIN_CFG)->select();
		$this->smarty->assign('data',$data);

		$html = $this->smarty->fetch('Events/eventsType.html');
		$this->ajaxReturn(array('status'=>0,'html'=>$html));
	}

	//类型添加
	public function eventsTypeAdd(){

		$names = I('get.names');
		$ids = I('get.ids');
		$eventsType = M('cfg_content_type',null,DB_MAIN_CFG);
		$newids = 0;
		foreach ($names as $key => $val){
			if($val){
				if(isset($ids[$key]) && intval($ids[$key]) > 0){
					$eventsType->where("id={$ids[$key]}")->save( array('name'=>$val) );
					$newids .= ','.$ids[$key];
				}else{
					$insertId = $eventsType->add( array('name'=>$val) );
					//指数统计表增加对应的字段
					M()->execute("ALTER TABLE star_core.statistic_user_like ADD index".$insertId." int(11) DEFAULT '0' COMMENT '系数对应cfg_content_type' ;");
					$newids .= ','.$insertId;
				}
			}
		}
		$eventsType->where(array('id'=>array('not in',$newids)))->delete();

		$this->ajaxReturn(array('status'=>0,'eventsTypeData'=>getContentTypeKv()));
	}

	private function getMoneyDiff($nowYear,$nowMonth,$targetYear,$targetMonth){
		if (!$targetMonth || !$targetYear){
			return '';
		}
		$months=($nowYear-$targetYear)*12+$nowMonth-$targetMonth;
		$year	= intval($months/12);
		$month	= $months%12;
		return "{$year}周岁{$month}月";
	}
	//报名列表
	public function applyList(){
		$where = " 1 ";
		//id为跳转活动id
		$id=I('get.id',0,'int');
		//eid为选择活动id
		$eid = I('get.eid',0,'int');
		$selectedID = 0;
		if($id > 0) {
			$selectedID = $id;
			$where .= " AND eid = '{$selectedID}' ";
		}
		if($eid > 0){
			$selectedID = $eid;
			$where .= " AND eid = '{$selectedID}' ";
		}
		$export = I('get.export',0,'int');
		$nickname = I('get.nickname',null);
		if($nickname){
			$where .= " AND nickname like '%$nickname%' ";
			$this->smarty->assign('nickname',$nickname);
		}

		$status = I('get.status',null);
		if($status){
			$where .= " AND e_events_join.status = '$status' ";
			$this->smarty->assign('status',$status);
		}

		$phone = I('get.phone',null);
		if($phone){
			$where .= " AND e_events_join.phone like '%$phone%' ";
			$this->smarty->assign('phone',$phone);
		}

		$useVip=I('get.useVip',0,'int');
		if($useVip==1){
			$where .= " AND e_events_join.useVip=1 ";
			$this->smarty->assign('useVip',$useVip);
		}


		$e_events_joinM = M("e_events_join",null,DB_MAIN_CFG);

		$where .= " AND e_events_join.del = 0 ";

		import("ORG.Util.Page");
		$temp=$e_events_joinM->join(" left join e_events on e_events.id = e_events_join.eid ")->where($where);
		$count = $temp->count();
		$this->smarty->assign('totalDataCount',$count);

		$limit = I('get.limit',10,'int');	//每页显示条数
		$Page = new Page($count,$limit);
		fetchPage($this->smarty, $Page);
		$ym=date('Y-m',time());
		list($nowYear,$nowMonth)=explode('-',$ym);

		if($export){
			if ($eid>0) {
				$msg = M('comment_' . OBJ_TYPE_ACTIVITY, null, DB_MAIN_CFG)->where("objID={$eid}")->group('uid')->getField("uid,GROUP_CONCAT(content SEPARATOR '          \r\n其它评论：')");
				$eventInfo = EventsModel::getEventInstance()->where(" id = '{$eid}'")->find();
			}

			$list = $e_events_joinM->field(" e_events_join.*,e_events.title,task")->join(" left join e_events on e_events.id = e_events_join.eid ")->order('e_events_join.status ASC,e_events_join.addTime DESC')->where($where)->select();
			$data = array();

			$field=array('活动名','用户ID','昵称','真实姓名','手机号码','报名时间','留言','宝宝信息','报名状态','作业状态','是否有分享图','图','配送地址');
			$selectAddress=false;
			if($eid>0 && $eventInfo && strlen($eventInfo['addressPool'])>0){
				$field[]='选择地址';
				$selectAddress=true;
			}
            $selectOther=false;
            if($eid>0 && $eventInfo && strlen($eventInfo['otherPool'])>0){
                $field[]=$eventInfo['otherTitle'];
                $selectOther=true;
            }

            $selectExt=false;
            if($eid>0 && $eventInfo && strlen($eventInfo['jsonData'])>0){
                $field[]='其它信息';
                $selectExt=true;
            }

			foreach ($list as $key => $val){
				$data[$key]['title'] = $val['title'];
				$data[$key]['uid'] = $val['uid'];
				$data[$key]['nickname'] = $val['nickname'];
				$data[$key]['realName'] = $val['realName'];
				$data[$key]['phone'] = $val['phone'];
				$data[$key]['addTime'] = date('Y-m-d H:i:s',$val['addTime']);
				$data[$key]['mark'] = $val['mark'];

				list($targetYear,$targetMonth)=explode('-',$val['babyBirthday']);
				$data[$key]['age']=$val['babyNickname']."\r\n".$val['babySex']."\r\n".$this->getMoneyDiff($nowYear,$nowMonth,$targetYear,$targetMonth);

				if ($eid>0) {
					if (array_key_exists($val['uid'],$msg)){
						$data[$key]['mark'].="          \n\r其它评论：   ".$msg[$val['uid']];
					}
				}

				$data[$key]['status'] =EventsModel::$userStatus[$val['status']];
				if($val['task']){
					$data[$key]['task'] =EventsModel::$taskStatus[$val['doTask']];
				} else{
					$data[$key]['task'] ="";
				}


				if(strlen($val['sharePic'])>5){
					$data[$key]['havePic'] = '有分享图片';
					$data[$key]['link'] = $val['sharePic'];
				}else{
					$data[$key]['havePic'] = '没有分享图片';
					$data[$key]['link'] = '';
				}
				$data[$key]['address'] = $val['street'].'.'.$val['address'];
				if ($selectAddress){
					$data[$key]['addressPool']=$val['addressPool'];
				}
                if ($selectOther){
                    $data[$key]['otherPool']=$val['otherPool'];
                }

                if ($selectExt){
                    $data[$key]['ext']=$val['ext'];
                }

			}
			exportExcel($data,$field ,'活动报名');
			exit;
		}
		else{			
			$list = $e_events_joinM->field(" e_events_join.*,e_events.title,e_events.task")->join(" left join e_events on e_events.id = e_events_join.eid ")->order('e_events_join.status ASC,e_events_join.addTime DESC')->where($where)->limit($Page->firstRow.','.$Page->listRows)->select();
			foreach ($list as $key=>$val){
				$list[$key]['applyCount'] = $e_events_joinM->where(" uid = '{$val['uid']}'")->count();//报名次数
				$list[$key]['applySelectedCount'] = $e_events_joinM->where(" uid = '{$val['uid']}' AND status = 2")->count();//被选中次数
				$list[$key]['applySelectedBadCount'] = $e_events_joinM->where(" uid = '{$val['uid']}' AND status = 4")->count();//不良记录
				$list[$key]['lastChosenTime'] = $e_events_joinM->where(" uid = '{$val['uid']}' AND status in (4,2)")->max('chosenTime');//最近一次入选时间

				list($targetYear,$targetMonth)=explode('-',$val['babyBirthday']);
				$list[$key]['age']=$this->getMoneyDiff($nowYear,$nowMonth,$targetYear,$targetMonth);
			}
			$this->smarty->assign('list',$list);
			$this->smarty->assign('id',$selectedID);

			$this->smarty->assign('statusArray',EventsModel::$userStatus);
			$this->smarty->assign('NEEDPAY',EventsModel::ORDER_PAY_STATUS_NEEDPAY);
			$this->smarty->assign('PAYEND',EventsModel::ORDER_PAY_STATUS_PAYEND);
			$this->smarty->assign('action','apply');
			$this->smarty->assign('limit',$limit);
			
			$eventKV=getEventsKv();

			$this->smarty->assign('eventKV',$eventKV);
			$this->smarty->display('Events/apply.html');
		}

	}

	//报名入选操作
	public function beSelected(){
		$id=I('get.id',0,'int');
		$flag=I('get.flag',0,'int');
		$e_events_joinM = M("e_events_join",null,DB_MAIN_CFG);
		$row = $e_events_joinM->where(" id = '{$id}' ")->find();
		if(!$row) $this->ajaxReturn( array('status'=>1, 'msg'=> '参数错误！') );

		$einfo = M("e_events",null,DB_MAIN_CFG)->where(" id = '{$row['eid']}' ")->find();
		$selectedUser = $e_events_joinM->where(" eid = '{$row['eid']}' AND  status = '".EventsModel::JOIN_STATUS_SELECTED."' AND del = 0 ")->count();//获取已入选的人数
		if($einfo['places']>0 && $einfo['places']<= $selectedUser){
			$this->ajaxReturn( array('status'=>1, 'msg'=> '名额已满哦！') );
		}

		if($flag == 0){
			$miner=$einfo['places']>0?$einfo['places']:'不限';
			$this->ajaxReturn( array('status'=>0, 'msg'=> "该活动名额为 {$miner}，已入选人数为 {$selectedUser} 个，确定让此人入选吗？") );
		}else{
			$e_events_joinM->where(" id = '{$id}' ")->save( array('status'=>EventsModel::JOIN_STATUS_SELECTED, 'chosenTime'=>time() ) );
			$repage = 1;
			if( ($selectedUser+1) == $einfo['places']){
				$e_events_joinM->where(" eid = '{$row['eid']}' AND status = '".EventsModel::JOIN_STATUS_APPLY."' AND del = 0  ")->save( array('status'=>EventsModel::JOIN_STATUS_UNSELECTED) );
				$repage = 0;
			}
			$this->ajaxReturn( array('status'=>0, 'repage'=> $repage) );
		}

	}

	//操作 用户报名状态(候选/未参加)
	public function uncommitted(){
		$id=I('get.id',0,'int');
		$status=I('get.status',0,'int');
		if(! $status || ! $id) $this->ajaxReturn( array('status'=>1) );//参数错误
		M("e_events_join",null,DB_MAIN_CFG)->where(" id = '{$id}' ")->save( array('status'=>$status) );
		$this->ajaxReturn( array('status'=>0) );
	}

	//查看用户详情(状态)
	public function userStatus(){
		$id = I("get.id",0,'int');
		$events_joinM = M("e_events_join",null,DB_MAIN_CFG);
		$einfo = $events_joinM->where(" id = '{$id}' ")->find();
		$uid = $einfo['uid'];
		$uInfo = M("u_user_base",null,DB_MAIN_CFG)->where(" uid = '{$uid}' ")->find();

		$applyCount = $events_joinM->where(" uid = {$uid}")->count();//报名次数
		$applySelectedCount = $events_joinM->where(" uid = {$uid} AND status = 2")->count();//被选中次数
		$applySelectedBadCount = $events_joinM->where(" uid = {$uid} AND status = 4")->count();//不良记录

		$LastChosenTime = $events_joinM->where(" uid = {$uid} AND addTime != 0 AND status IN(2,4) ")->order(" addTime DESC")->find();//报名次数

		$this->smarty->assign('getLevelKv',getLevelKv());
		$this->smarty->assign('getUTagKv',getUTagKv());
		$this->smarty->assign('getVipKv',getVipKv());
		$this->smarty->assign('LastChosenTime', $LastChosenTime);
		$this->smarty->assign('applyCount', $applyCount);
		$this->smarty->assign('applySelectedCount', $applySelectedCount);
		$this->smarty->assign('applySelectedBadCount', $applySelectedBadCount);

		$this->smarty->assign('einfo', $einfo);

		$uInfo['address'] = UtilsModel::getRegionNameByProvince($uInfo,'-');

		$this->smarty->assign('uInfo', $uInfo);

		$html = $this->smarty->fetch('Events/userStatus.html');
		$this->ajaxReturn(array('status'=>0, 'dataHTML'=>$html));
	}

	public function uploadPhoto(){
		$eid=I('get.eid',0,'int');
		$uid=I('get.uid',0,'int');

		$list=EventsModel::getPhotoInstance()->where("eid={$eid} and uid={$uid}")->select();


		$this->smarty->assign('eid',$eid);
		$this->smarty->assign('uid',$uid);
		$this->smarty->assign('list',$list);
		$this->smarty->display('Events/uploadPhoto.html');
	}

	/**
	 * 保存后台用户标注
	 */
	public function saveMem(){
		$uid=I("post.uid",0,'int');
		if ($uid==0){
			$this->ajaxReturn(array('status'=>1, 'msg'=>"未指定用户"));
		}
		$mem=I("post.mem",'');
		UserModel::getInstance()->where("uid={$uid}")->setField("adminMem",$mem);
		$this->ajaxReturn(array('status'=>0, 'msg'=>"保存成功"));
	}


	/**
	 * 增加报名
	 */
	public function addApply(){
		$eid=I('get.eid',0,'int');
		$uid=I('get.uid',0,'int');
		
		$result=EventsModel::adjustApply($eid,$uid);
		$this->ajaxReturn($result);
	}
	
	
	public function changeAdjust(){
		$eid=I('get.eid',0,'int');
		$num=I('get.num',0,'int');

		$result=EventsModel::changeAdjustHot($eid,$num);
		if ($result==false) {
			$this->ajaxReturn(array('status'=>1));
		}else{
			$this->ajaxReturn(array('status'=>0));
		}
	}

	/**
	 * 取消报名
	 */
	public function  cancelApply(){
		$id=I('get.id',0,'int');
		$row = EventsModel::getJoinInstance()->where(" id = '{$id}' ")->field("eid,uid")->find();
		$result=EventsModel::cancelRegistration($row['eid'],$row['uid']);
		$this->ajaxReturn($result);
	}


	public function saveEventPhoto(){
		$uid=I("post.uid",0,'int');
		$eid=I("post.eid",0,'int');
		if ($eid==0){
			$this->ajaxReturn(array('status'=>1,'msg'=>"必须指定活动"));
		}
		$pics=I('post.pic',null);
		$data=array();
		foreach ($pics as $pic){
			$data[]=array('eid'=>$eid,'uid'=>$uid,'path'=>$pic);
		}
		$m=EventsModel::getPhotoInstance();
		$m->startTrans();
		$m->where("eid={$eid} and uid={$uid}")->delete();

		if(count($pics)>0 && false==$m->addAll($data)){
			$m->rollback();
			$this->ajaxReturn(array('status'=>1,'msg'=>"更新失败"));
		}
		$m->commit();
		$this->ajaxReturn(array('status'=>0,'msg'=>"修改成功"));

	}


	//未交作业，发送客服提醒
	public function noTaskSendMessage()
	{
		$id = I("get.id", 0, 'int');
		$events_joinM = M("e_events_join", null, DB_MAIN_CFG);
		$einfo = $events_joinM->where(" id = '{$id}' ")->find();

		$data['uid'] = $einfo['uid'];
		$data['eid'] = $einfo['eid'];
		$data['openID'] = M('u_user_weixin', null, DB_MAIN_CFG)->where("uid = '{$data['uid']}'")->getField("WX2_openID");
		$title = M('e_events', null, DB_MAIN_CFG)->where("id = '{$data['eid']}'")->getField('title');
		$data['content'] = "您参与的\"" . $title . "\"活动还未提交作业，请尽快去提交！";
		$data['addTime'] = time();
		$startTime = date("Y-m-d H:i:s", strtotime("-1 day"));


		$smsM = M('weixin_sms_log', null, DB_MAIN_CFG);
		if ($smsM->where("eid='{$data['eid']}' and openID='{$data['openID']}' and addTime between '{$startTime}' and '{$data['addTime']}'")->find()) {
			$this->ajaxReturn(array('status' => 1, 'msg' => "您已在24小时内发送短信提醒，请稍后再试"));
		}
		$res = WeixinModel::sendCustom_text($data['openID'], $data['content']);
		if ($res['status'] == 1) {
			$this->ajaxReturn(array('status' => 1, 'msg' => $res['msg']));
		} else {
			$smsM->add($data);
			$this->ajaxReturn(array('status' => 0, 'msg' => "发送成功"));
		}
	}

	//读取作业详情
	public function getTaskInfo(){
//		$id = I('get.id',0,'intval');
		$eid = I('get.eid',0,'intval');
		$uid = I('get.uid',0,'intval');

		if(!$eid || !$uid){
			$this->ajaxReturn(array('status'=>1,'msg'=>"无效参数"));
		}

		$info = M('e_events_task',null,DB_MAIN_CFG)->where("eid={$eid} and uid={$uid}")->find();
		$info['title'] = M('e_events',null,DB_MAIN_CFG)->where("id={$eid}")->getField("title");
		$info['imgList'] = explode(',',$info['imgList']);
		$this->smarty->assign('info',$info);
		$html =$this->smarty->fetch("Events/task.html");
		$this->ajaxReturn(array('status'=>0,'dataHtml'=>$html));
	}

	//改变作业考核状态
	public function changeTaskStatus(){
		$status = I('get.status',1,'intval');
		$eid = I('get.eid',0,'intval');
		$uid = I('get.uid',0,'intval');
		$return = M('e_events_task',null,DB_MAIN_CFG)->where("eid={$eid} and uid={$uid}")->setField('status',$status);
		if($return !== false){
			if($return==1){

				if ($status==1){
					//作业内容同步到商家评论
					$relatedStore=M('e_events',null,DB_MAIN_CFG)->where("id={$eid}")->getField('relatedStore');
					if ($relatedStore>0){
						$task=M('e_events_task',null,DB_MAIN_CFG)->where("eid={$eid} and uid={$uid}")->find();
						$uinfo = array(
							'uid'=>$uid,
							'nickname'=>UserModel::getInstance()->where('uid='.$uid)->getField('nickname')
						);
						CommentModel::commentNew(OBJ_TYPE_STORE, $relatedStore, 0, $task['content'], $uinfo,0,$task['imgList']);
					}
				}




				$this->ajaxReturn(array('status'=>0,'msg'=>"更改成功"));
			}else{
				$this->ajaxReturn(array('status'=>0));
			}
		} else{
			$this->ajaxReturn(array('status'=>1,'msg'=>"更改失败"));
		}
	}
}




